﻿using System;
using System.Collections.Generic;
using System.Windows.Threading;

namespace MyWindowsMediaPlayer.Libs.Mediator
{
	public class Mediator : DispatcherObject
	{
		#region Fields

		readonly MessageToActionsMap _messageToCallbacksMap;

		#endregion

		#region Constructor

		public Mediator ( )
		{
			if (base.Dispatcher == null)
				throw new InvalidOperationException("Cannot create Mediator on a thread that does not have a Dispatcher.");

			_messageToCallbacksMap = new MessageToActionsMap();
		}

		#endregion

		#region Methods

		public void Register ( object message, Action<object> callback )
		{
			if (message == null)
				throw new ArgumentNullException("message");

			if (callback == null)
				throw new ArgumentNullException("callback");

			if (callback.Target == null)
				throw new ArgumentException("The 'callback' delegate must reference an instance method.");

			_messageToCallbacksMap.AddAction(message, callback);
		}

		public void NotifyColleagues ( object message, object parameter )
		{
			if (base.CheckAccess())
			{
				List<Action<object>> actions =
					_messageToCallbacksMap.GetActions(message);

				if (actions != null)
					actions.ForEach(action => action(parameter));
			}
			else
			{
				base.Dispatcher.BeginInvoke((Action)delegate
				{
					this.NotifyColleagues(message, parameter);
				},
				DispatcherPriority.Send);
			}
		}

		#endregion // Methods
	}
}
